package com.freemalll.merchant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.domain.dto.RegisterStepDto;
import com.freemalll.merchant.domain.entity.MerMerchantRegisterStep;
import com.freemalll.merchant.mapper.MerMerchantRegisterStepMapper;
import com.freemalll.merchant.service.MerMerchantRegisterStepService;
import com.freemalll.merchant.utils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 服务层实现。
 *
 * @author songshixiong
 * @since 2025-05-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MerMerchantRegisterStepServiceImpl extends ServiceImpl<MerMerchantRegisterStepMapper, MerMerchantRegisterStep> implements MerMerchantRegisterStepService {

    @Override
    public List<RegisterStepDto> listByMerId(String merId) {
        return baseMapper.listByMerId(merId);
    }

    @Override
    public void createSupplementaryPartsFlow(String merId) {
        //将最新的步骤设置为非最新
        MerMerchantRegisterStep merMerchantRegisterStep = baseMapper.selectOne(Wrappers.<MerMerchantRegisterStep>lambdaQuery()
                .eq(MerMerchantRegisterStep::getMerId, merId)
                .eq(MerMerchantRegisterStep::getCurrentFlag, true));
        if (merMerchantRegisterStep != null) {
            merMerchantRegisterStep.setCurrentFlag(false);
            baseMapper.updateById(merMerchantRegisterStep);
        }
        //新增补件步骤并设置为最新
        MerMerchantRegisterStep supplementaryPartsStep = new MerMerchantRegisterStep();
        supplementaryPartsStep.setMerId(merId);
        supplementaryPartsStep.setStepName("补件");
        supplementaryPartsStep.setCompleteFlag(false);
        supplementaryPartsStep.setStepType(CommonEnum.cooperationApplyStepType.SUPPLEMENTARY_PARTS.name());
        supplementaryPartsStep.setOrderNo(merMerchantRegisterStep.getOrderNo() + 1);
        supplementaryPartsStep.setCurrentFlag(true);
        if ("补件".equals(merMerchantRegisterStep.getStepName())) {
            BeanUtils.copyPropertiesIgnoreNull(supplementaryPartsStep, merMerchantRegisterStep);
            baseMapper.updateById(merMerchantRegisterStep);
        } else {
            baseMapper.insert(supplementaryPartsStep);

        }
    }
    }

